const AccommodationService = require('../services/accommodationService');

// 获取所有可用的住宿信息
exports.getAccommodationList = async (ctx) => {
  try {
    const { scenic_id, category, page, limit } = ctx.query;
    const accommodations = await AccommodationService.getAccommodationList(scenic_id, category, page, limit);
    ctx.status = 200;
    ctx.body = {
      code: 200,
      message: "获取成功",
      data: accommodations
    };
  } catch (error) {
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: "获取失败",
      error: error.message
    };
  }
};

// 获取单个住宿信息的详细内容
exports.getAccommodationById = async (ctx) => {
  try {
    const { id } = ctx.params;
    const accommodation = await AccommodationService.getAccommodationById(id);
    ctx.status = 200;
    ctx.body = {
      code: 200,
      message: "获取成功",
      data: accommodation
    };
  } catch (error) {
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: "获取失败",
      error: error.message
    };
  }
};

// 创建一个新的住宿信息
exports.createAccommodation = async (ctx) => {
  try {
    const accommodationData = ctx.request.body;
    const accommodation = await AccommodationService.createAccommodation(accommodationData);
    ctx.status = 201;
    ctx.body = {
      code: 201,
      message: "住宿信息创建成功",
      data: { accommodation_id: accommodation.id }
    };
  } catch (error) {
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: "创建失败",
      error: error.message
    };
  }
};

// 用户预定住宿
exports.bookAccommodation = async (ctx) => {
  try {
    const bookingData = ctx.request.body;
    const booking = await AccommodationService.bookAccommodation(bookingData);
    ctx.status = 201;
    ctx.body = {
      code: 201,
      message: "预订成功",
      data: { reservation_id: booking.reservation_id }
    };
  } catch (error) {
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: "预订失败",
      error: error.message
    };
  }
};

// 获取用户预定的住宿记录
exports.getUserReservations = async (ctx) => {
  try {
    const { user_id } = ctx.params;
    const reservations = await AccommodationService.getUserReservations(user_id);
    ctx.status = 200;
    ctx.body = {
      code: 200,
      message: "获取成功",
      data: reservations
    };
  } catch (error) {
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: "获取失败",
      error: error.message
    };
  }
};

// 取消预订
exports.cancelReservation = async (ctx) => {
  try {
    const { user_id, reservation_id } = ctx.request.body;
    const result = await AccommodationService.cancelReservation(user_id, reservation_id);
    ctx.status = 200;
    ctx.body = {
      code: 200,
      message: result.message
    };
  } catch (error) {
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: "取消预订失败",
      error: error.message
    };
  }
};
